import request from '@/utils/request'
import { defineStore } from 'pinia'
import { CategoryItem, ApiRes, TopCategory, SubCategory } from '@/types/data'
import { topCategory } from '@/config/constant'

const defaultCategory = topCategory.map((item) => ({ name: item }))

const useCategoryStore = defineStore('category', {
	state: () => {
		return {
			list: defaultCategory as CategoryItem[],
			activeId: '0',
			// 顶级分类
			topCategory: {} as TopCategory,
			// 二级分类
			subCategory: {} as SubCategory,
		}
	},
	actions: {
		async getAllCategory() {
			const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
			res.data.result.forEach((item) => (item.open = false))
			this.list = res.data.result
		},
		show(id: string) {
			const category = this.list.find((item) => item.id === id)! // 使用非空断言
			category.open = true
		},
		hide(id: string) {
			if (id !== '0') {
				const category = this.list.find((item) => item.id === id)! // 使用非空断言
				category.open = false
			}
			this.activeId = id
		},
		async getTopCategory(id: string) {
			const res = await request.get<ApiRes<TopCategory>>('/category', {
				params: {
					id,
				},
			})
			this.topCategory = res.data.result
		},
		async getSubCategory(id: string) {
			const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
				params: {
					id,
				},
			})
			this.subCategory = res.data.result
		},
	},
	getters: {},
})
export default useCategoryStore
